package com.huicoo.forestmanager.ui.login;

import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.text.TextUtils;
import android.widget.EditText;

import com.huicoo.forestmanager.CustomUtils;
import com.huicoo.forestmanager.R;
import com.huicoo.forestmanager.network.HttpService;
import com.huicoo.forestmanager.others.Constants;
import com.huicoo.forestmanager.ui.login.contract.LoginContract;
import com.huicoo.forestmanager.ui.login.presenter.LoginPresenter;
import com.huicoo.forestmanager.base.BaseActivity;
import com.huicoo.forestmanager.ui.main.MainActivity;
import com.huicoo.forestmanager.util.LogUtils;
import com.huicoo.forestmanager.util.SharedPreferenceUtil;
import com.huicoo.forestmanager.util.WeakHandler;
import com.huicoo.forestmanager.util.toast.ToastUtils;
import com.huicoo.forestmanager.widget.BaseUrlSettingDialog;
import com.huicoo.forestmanager.widget.LoadingDialog;

import org.json.JSONObject;

import java.io.IOException;
import java.util.HashMap;

import butterknife.BindView;
import butterknife.OnClick;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;

/**
 * --------- 日期 ------- 维护人 ------------ 变更内容 --------
 * 2019/4/7		    Administrator
 * 登陆页面
 */
public class LoginActivity extends BaseActivity implements LoginContract.View, Handler.Callback {
    @BindView(R.id.et_account)
    EditText et_account;
    @BindView(R.id.et_password)
    EditText et_password;

    private LoadingDialog loadingDialog;
    private WeakHandler handler;
    private HashMap<String, String> urlMap = new HashMap<>();
    private boolean isShowUrlDialogRightNow; //是否在获取通道配置信息后就弹窗设置窗口

    @Override
    protected int getLayoutId() {
        return R.layout.activity_login;
    }

    @Override
    protected void initView() {
        presenter = new LoginPresenter(this);
        if (loadingDialog == null) {
            loadingDialog = new LoadingDialog(this);
        }

        handler = new WeakHandler(this);

        String account = SharedPreferenceUtil.LoadStringData(Constants.PROJECT_NAME, Constants.USER_ACCOUNT);
        if (!TextUtils.isEmpty(account)) {
            et_account.setText(account);
            et_account.setSelection(account.length());
        }

        //请求通道配置信息
        if (loadingDialog != null) {
            loadingDialog.show();
        }
        requestBaseUrlSetting(1);
    }

    @OnClick(R.id.tv_forget_password)
    public void clickForgetPassword() {
        ToastUtils.show("请联系当地林长办重置密码");
    }

    @OnClick(R.id.tv_login)
    public void clickLogin() {
        String account = et_account.getText().toString().trim();
        String password = et_password.getText().toString().trim();
        if (TextUtils.isEmpty(account)) {
            ToastUtils.show("请输入用户名");
            return;
        }
        if (TextUtils.isEmpty(password)) {
            ToastUtils.show("请输入密码");
            return;
        }
        loadingDialog.show();
        ((LoginPresenter) presenter).login(account, password);
    }

    @OnClick(R.id.iv_setting)
    public void clickSetting() {
        if (urlMap.isEmpty()) {
            isShowUrlDialogRightNow = true;
            //请求通道配置信息
            if (loadingDialog != null) {
                loadingDialog.show();
            }
            requestBaseUrlSetting(0);
        } else {
            showUrlDialog();
        }
    }

    @Override
    public void loginSuccess() {
        ToastUtils.show("登录成功");
        loadingDialog.dismiss();
        Intent intent = new Intent(this, MainActivity.class);
        startActivity(intent);
        finish();
    }

    @Override
    public void loginFail(String msg) {
        ToastUtils.show(msg);
        loadingDialog.dismiss();
    }

    private void requestBaseUrlSetting(int isInit) {
        String url = "http://47.110.80.118/CommSvc/GetValue.aspx?type=commonstr&key=forestapp_weburl&format=json";
        LogUtils.v("gogogo get base url = " + url);
        OkHttpClient okHttpClient = new OkHttpClient();
        final Request request = new Request.Builder()
                .url(url)
                .get()
                .build();
        Call call = okHttpClient.newCall(request);
        call.enqueue(new Callback() {

            @Override
            public void onResponse(@NonNull Call call, @NonNull Response response) {
                Message msg = new Message();
                msg.what = 200;
                msg.obj = response.body();
                msg.arg1 = isInit;
                handler.sendMessage(msg);
            }

            @Override
            public void onFailure(@NonNull Call call, @NonNull IOException e) {
                e.printStackTrace();
                Message msg = new Message();
                msg.what = 500;
                msg.arg1 = isInit;
                handler.sendMessage(msg);
            }

        });
    }

    private void showUrlDialog() {
        BaseUrlSettingDialog dialog = new BaseUrlSettingDialog(LoginActivity.this);
        dialog.setOnSetBaseUrlListener(new BaseUrlSettingDialog.OnSetBaseUrlListener() {
            @Override
            public void confirm(String key, String baseUrl) {
                SharedPreferenceUtil.putData(Constants.PROJECT_NAME, Constants.BASE_URL_KEY, key);
                SharedPreferenceUtil.putData(Constants.PROJECT_NAME, Constants.BASE_URL, baseUrl);
                HttpService.resetHttpService();
                ToastUtils.show("通道设置完成");
                dialog.dismiss();
            }
        });
        dialog.showDialog(urlMap);
    }

    @Override
    public boolean handleMessage(Message msg) {
        switch (msg.what) {
            case 200: {
                boolean isShowMsg = msg.arg1 != 1;
                try {
                    if (loadingDialog != null) {
                        loadingDialog.dismiss();
                    }
                    if (msg.obj != null) {
                        ResponseBody body = (ResponseBody) msg.obj;
                        String json = body.string();
                        LogUtils.v("gogogo get base url result = " + json);
                        if (!TextUtils.isEmpty(json)) {
                            JSONObject jsonObject = new JSONObject(json);
                            int State = jsonObject.optInt("State", 0);
                            if (State == 1) {
                                String Data = jsonObject.optString("Data", "");
                                if (!TextUtils.isEmpty(Data)) {
                                    String[] mUrls = Data.split(";");
                                    urlMap.clear();
                                    for (String mUrl : mUrls) {
                                        if (mUrl.contains(",")) {
                                            String[] mapContent = mUrl.split(",");
                                            if (mapContent.length == 2) {
                                                LogUtils.v("gogogo key value = " + mapContent[0] + "     " + mapContent[1]);
                                                urlMap.put(mapContent[0], mapContent[1]);
                                            }
                                        }
                                    }
                                    //设置默认base url
                                    if (TextUtils.isEmpty(CustomUtils.getBaseUrl())) {
                                        String initBaseUrl = urlMap.get("8888");
                                        SharedPreferenceUtil.putData(Constants.PROJECT_NAME, Constants.BASE_URL_KEY, "8888");
                                        SharedPreferenceUtil.putData(Constants.PROJECT_NAME, Constants.BASE_URL, initBaseUrl);
                                        HttpService.resetHttpService();
                                    }
                                    //判断是否需要在请求成功后弹窗
                                    if (isShowUrlDialogRightNow) {
                                        showUrlDialog();
                                        isShowUrlDialogRightNow = false;
                                    }
                                } else {
                                    if (isShowMsg) {
                                        ToastUtils.show("暂无配置信息");
                                    }
                                }
                            } else {
                                if (isShowMsg) {
                                    ToastUtils.show("获取通道配置失败");
                                }
                            }
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    if (isShowMsg) {
                        ToastUtils.show("获取通道配置失败");
                    }
                }
                break;
            }
            case 500: {
                if (loadingDialog != null) {
                    loadingDialog.dismiss();
                }
                boolean isShowMsg = msg.arg1 != 1;
                if (isShowMsg) {
                    ToastUtils.show("获取通道配置失败");
                }
                break;
            }
            default:
                break;
        }
        return false;
    }
}
